package com.zangchat.utils;

import com.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {


    @Autowired
    private RedisTemplate redisTemplate;


    public void set(final String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key,value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public void set(String key, Object value, Long time) {
//        redisTemplate.opsForValue().set(key, value);
        if (time > 0) {
//            redisTemplate.expire(key, time, TimeUnit.SECONDS);
            value=value+"";
            redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
        }
    }

    /**
     * 判断是否是key值
     *
     * @param key
     * @return
     */
    public Boolean isKeyInCache(final String key) {
        return redisTemplate.hasKey(key);
    }

    public Object get(final String key) {
        Object result = null;
        result = redisTemplate.boundValueOps(key).get();
        if (result == null) {
            return null;
        }
        set(key, result);
        return result;
    }

    public Object simpleGet(final String key){
        Object result = null;
        result = redisTemplate.boundValueOps(key).get();
        if (result == null) {
            return null;
        }
        return result;
    }


    public void remove(String key) {
        if (isKeyInCache(key)) {
            redisTemplate.delete(key);
        }
        ;
    }

    public void update(String key, Object value) {
//        Element element = new Element(key, value);
        set(key, value);
    }
    public void update(String key, Object value,Long time) {
//        Element element = new Element(key, value);
        set(key, value);
        if(time>0){
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }

    /*根据业务创建key*/
    public String createKey(String... arg){
        String prefix="";
        for (int i = 0; i < arg.length; i++) {
            prefix=prefix+arg[i]+"-";
        }
        return prefix.substring(0,prefix.length()-1);
    }

    /**
     * 减少值
     * */
    public  Long increment( String key) {
       return  redisTemplate.opsForHash().increment(key, "", 1);
    }

    public boolean checkUserId(Long userId,String derviceId){
        Object oldDerviceId = get(userId+"");
         if (derviceId.equals(oldDerviceId)){
            return true;
        }else {
            return false;
        }
    }

}
